var selectValue="",iDisplayStart=0,iDisplayLength=10,totalPageNum,pageNum=0,pageFlag=false,getHamidFlag=false,companyName="",getProjectId;
//分页初始化数据;
var pagition=function(obj,start,target){
	var globalSearch = {};
	var searchConditions = {};
	var aoData=[];
	if($.trim(obj)!=''){
		searchConditions.queryValue=obj;
	}
	searchConditions.queryName='USERNAME';
	globalSearch.name= 'globalSearch';
	globalSearch.value= JSON.stringify(searchConditions);
	aoData.push(globalSearch);
	$.ajax({
		type:"get",
		contentType : "application/x-www-form-urlencoded; charset=UTF-8", 
		url:baseURL+'/api/member/list?iDisplayStart='+start*iDisplayLength+'&iDisplayLength='+iDisplayLength+'&t='+new Date().getTime(),
		data:aoData,
		dataType:"JSON",
		success:function(result){
			if(result.flag){
				if(result.results.length!=0){
					$(target).find('ul.pagitionList').empty();
					$.each(result.results,function(i,n){
						var tmp = n.username;
						var name = n.username;
						if(n.name!=null&&n.name!=""){
							tmp = n.name+"("+tmp+")";
							name=n.name;
						}
						$(target).find('ul.pagitionList').append("<li uid='"+n.id+"' uname='"+name+"'>"+tmp+"</li>");
					})
					$(target).find('ul.pagitionList').find('li').on('click',function(e){
						e.stopPropagation();
						$(e.target).parent().parent().prev().val($(e.target).attr("uname")).focus();
						$(e.target).parent().parent().prev().attr("name",$(e.target).attr("uid"));
						$(e.target).parent().parent().attr("name",$(e.target).attr("uid"));
						$(e.target).parent().find('li').removeClass("airportSelectBK");
						$(e.target).addClass("airportSelectBK");
						if($(e.target).parents("form#projectAdd_firstFrom")){
							$.ajax({
								type:'get',
								url:baseURL+'/api/member/getMemberDetail/'+$(e.target).attr("uid"),
								datatype:'json',
								success:function(result){
									if(result.flag){
										var obj=result.result;
										$('#projectMember_info').html("项目负责人："+obj.fullName+",手机号："+obj.mobile+(obj.provinceName==""?"":","+obj.provinceName)+(obj.cityName==""?"":","+obj.cityName)+obj.company);
										companyName=obj.company;
									}
								},
								error:function(data){
									
								}
							})
						}
					})
				}else {
					$(target).find('ul.pagitionList').empty().append("<li>没有数据</li>")
				}
				$(target).show();
				$(target).find('ul.pagitionList').show();
			}else layer.msg("数据报错："+result.message);
			totalPageNum=Math.floor(result.totalcount/iDisplayLength);
			if(totalPageNum>0){
				$(target).find('.pagitionController').show();	
			}else $(target).find('.pagitionController').hide();
		}
	  })
	}
$(function () {
	provinceInfo.baseURL = baseURL;
	provinceInfo.divId = "test";
	provinceInfo.init();
	provinceInfo.bindEvent();
	$(".projectAdd_sPL").find("div:first").css('width','56px');
	$("input").attr('autocomplete','off');
	$("input").on('click,keyup',function(e){
		e.preventDefault();
	});
	$.ajax({
		type:'get',
		datatype:'json',
		url:baseURL+'/api/dict/dict/500001',
		success:function(result){
			if(result.flag){
				$.each(result.results,function(i,n){
					$("#productTypeCode").append("<option value='"+n.dictItemCode+"'>"+n.dictItemName+"</option>")
				})
			}
		}
	})
	$.ajax({//来源
		type:'get',
		datatype:'json',
		url:baseURL+'/api/dict/dict/600000',
		success:function(result){
			if(result.flag){
				$.each(result.results,function(i,n){
					$("#infoFrom").append("<option value='"+n.dictItemCode+"'>"+n.dictItemName+"</option>")
				})
			}
		}
	})
	$.ajax({
		type:'get',
		datatype:'json',
		url:baseURL+'/api/dict/dict/500002',
		success:function(result){
			if(result.flag){
				$.each(result.results,function(i,n){
					$("#userGroupCode").append("<option value='"+n.dictItemCode+"'>"+n.dictItemName+"</option>")
				})
			}
		}
	})
	
	$('.nextPagition').on('click',function(e){
		e.stopPropagation();
		++pageNum;
		if(pageNum>totalPageNum){
			pageNum=totalPageNum
			$(e.target).addClass('disabled')
			return;
		}else{
			$(e.target).removeClass('disabled')
			pagition(selectValue,pageNum,$(e.currentTarget).parent().parent());
		}
	})
	var isMouse=true;
	$('.prevPagition').on('click',function(e){
		e.stopPropagation();
		--pageNum;
		if(pageNum<=-1){
			pageNum=0;
			$(e.target).addClass('disabled')
			return;
		}else{
			$(e.target).removeClass('disabled')
			pagition(selectValue,pageNum,$(e.currentTarget).parent().parent());
		}
	})
	$(".projectDrownSearch").on('click',function(e){
		e.stopPropagation();
		pagition($(e.target).val(),0,$(e.target).next());
		pageNum=0;	
	})
	$(".projectDrownSearch").on('keyup',function(e){
		e.stopPropagation();
		pageNum=0;
		pageFlag=true;
		selectValue=$(e.target).val();
		pagition($(e.target).val(),0,$(e.target).next());
	})
	$('.pagitionDiv').on('mouseleave',function(e){
		e.stopPropagation();
		$(e.currentTarget).hide();
		isMouse=true;
	})
	$('.pagitionDiv').on('mouseover',function(e){
		e.stopPropagation();
		isMouse=false;
	})
	$('.projectDrownSearch').on('blur',function(e){
		e.stopPropagation();
		if(isMouse){
			$(e.target).next().hide();
		}
	})
    $("#projectAdd_firstFrom").Validform({
        tiptype: 1,
        showAllError: true,
        datatype: {
            "empty": /^\s*$/,
            "code": /^[a-z0-9A-Z_-]{1,16}$/
        },
        beforeCheck:function(form){
        	/*if($('#username').val()==""){
        		$('#username').attr('name','');
        	}
        	*/
    	},
        callback: function (form) {
            layer.confirm('您确定要提交表单吗?', function () {
                _submitFirst();
            })
            return false;
        }
    });
    $("#projectAdd_secoundFrom").find("form").Validform({
        tiptype: 1,
        showAllError: true,
        datatype: {
            "empty": /^\s*$/,
            "code": /^[a-z0-9A-Z_-]{1,16}$/
        },
        beforeCheck:function(form){
        	var isFlag=false;
        	$.each($(form).find('input.projectDrownSearch'),function(i,n){
        		if($(n).val()==""){
        			$(n).attr('name','');
            	}
            	if($(n).attr('name')==""){
                	layer.msg("请从下拉菜单中选择一个");
                	$(n).focus();
                	isFlag=true;
                	return false;
                }
        	})
        	if(isFlag){
        		return false;
        	}else return true;
        },
        callback: function (form) {
            layer.confirm('您确定要提交表单吗?', function () {
                _submitSecound(form);
            })
            return false;
        }
    });
})
_submitFirst = function () {
    var data = {};

	data.drugName = $('#drugName').val();
    data.commonName = $('#commonName').val();
	data.englishName = $('#englishName').val();
	
	data.chineseSpell = $('#chineseSpell').val();
    data.character = $('#character').val();
	data.indication = $('#indication').val();
    data.element = $('#element').val();
    data.usageDosage = $('#usageDosage').val();
    data.taboo = $('#taboo').val();
    data.attention = $('#attention').val();
    data.drugInteraction = $('#drugInteraction').val();
    $.ajax({
        type: "post",
        url: baseURL+"/api/drugs/saveOrgUpdateDrugs",
        dataType: "json",
        contentType: "application/json;charset=UTF-8", 
        data: JSON.stringify(data),
        success: function (result) {
            if (!result.flag) {
                layer.msg("增加失败！原因：" + result.message);
                return;
            }
            layer.msg('提交成功',1,1);
            parent.location.reload();
            window.close();
        },
        error:function(errormsg){
			layer.msg("数据出错："+JSON.stringify(errormsg));
		}
    });
}

_submitSecound = function (obj) {
    var data ={};
    switch($(obj).attr("val"))
	{
	case "500000-0001":
		data.infoFrom = $(obj).find(".infoFrom").val();
		data.enteringMan = $(obj).find(".enteringMan").attr('name');
		data.followResult = $(obj).find(".followResult").val();
		break;
	case "500000-0002":
		var filepath=$('#attachment').val();
		if(filepath!=''){
			var extStart=filepath.lastIndexOf(".");
			var ext=filepath.substring(extStart,filepath.length).toUpperCase();
		}
		break;
	case "500000-0003":
		data.testResult = $(obj).find(".testResult").val();
		break;
	case "500000-0004":
		data.prototypeAmount = $(obj).find(".prototypeAmount").val();
		data.prototypeResult = $(obj).find(".prototypeResult").val();
		break;
	case "500000-0005":
		data.ensureResult = $(obj).find(".ensureResult").val();
		break;
	case "500000-0006":
		data.littleBathResult = $(obj).find(".littleBathResult").val();
		break;
	case "500000-0007":
		data.bathProductResult = $(obj).find(".bathProductResult").val();
		break;
	default :
		layer.msg("数据出错:"+n.errormessage);
	}
    data.projectId=getProjectId;
    data.progressTypeCode=$(obj).attr("val");
    data.followTime = $(obj).find(".Wdate").val();
	data.onlineFollowMan = $(obj).find(".onlineFollowMan").attr('name');
	data.offlineFollowMan = $(obj).find(".offlineFollowMan").attr('name');
	data.id=$(obj).attr('pid');
	$.ajaxFileUpload({
		type:"post",
		url: baseURL+"/api/project/saveOrgUpdatePrjProgress",
		secureuri : false,
		fileElementId : 'attachment',
		data: data,
		dataType : 'text/json',
		success : function(result, status) {
			console.log("编辑进度返回数据"+result);
			result=JSON.parse(result);
            if(''==result.pId){
            	layer.msg("更新失败！原因：" + result.message);	
            	return ;
            }else{
            	$(obj).attr('pid',result.pId);
            	 layer.msg('提交成功',1,1);
            	 return ;
            }
		},
		error : function(errormsg) {
			layer.msg("数据出错："+JSON.stringify(errormsg));
		}
	}); 
	

}
